/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Alert;
import com.riq.entity.Member;

	public class AndroidHandlerServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(VoicemailHandlerServlet.class.getName());

	  @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws IOException { 


   // ---------------------------------------------------------------------------------------------
   //  HEADER: ANDROID
   // ---------------------------------------------------------------------------------------------

        String deptId = request.getParameter("deptId");
        String alertId = request.getParameter("alertId");
        String action = "";
        
        log.info("Inside doPost");
        Properties props = new Properties(); 
        Session session = Session.getDefaultInstance(props, null); 
        Message msg = null;
        try {
          msg = new MimeMessage(session, request.getInputStream());
          action = msg.getSubject();
          
        } catch (MessagingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        
        log.info("Inside AndroidMailServlet");

    // ---------------------------------------------------------------------------------------------
    //  METHOD DIRECTORY: STATUS
    // ---------------------------------------------------------------------------------------------

        if ("riqResendAlert".equalsIgnoreCase(action)) { 
          riqDirections(response, request, alertId, msg); 
//        } else if ("riqAndroidRespYes".equalsIgnoreCase(action)) { 
//          riqRespYes(response, request, deptId); 
//        } else if ("riqAndroidRespNo".equalsIgnoreCase(action)) { 
//          riqRespNo(response, request, deptId); 
//        } else if ("riqAndroidResend".equalsIgnoreCase(action)) { 
//          riqResendAlert(response, request, deptId, msg); 
//        } else if ("riqAndroidGPS".equalsIgnoreCase(action)) { 
//          riqGPS(response, request); 
//        } else if ("riqAndroidOOS".equalsIgnoreCase(action)) { 
//          riqOOS(response, request);
        } else {
          
          log.info("end");
          
        }
    }
              
        
  private void riqDirections(HttpServletResponse response, ServletRequest request, 
        String alertId, Message msg) {
          
    try {
    
    //    log.info("MsgContent: " + msg.getContent().toString().substring(0, 50));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(51, 100));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(101, 150));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(151, 200));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(201, 250));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(251, 300));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(301, 350));
    //    log.info("MsgContent: " + msg.getContent().toString().substring(351, 400));
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    String alertText = "";
    try {
      alertText = getText(msg);
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    
    // Text Message
    Address[] fromAddress = msg.getFrom(); 
    String fromAddressString = fromAddress.toString();
    fromAddressString = fromAddressString.replaceAll("\\D","");
    String callerId = fromAddressString.substring(12, 22).trim();
    log.info("callerId.trim: " + callerId.trim());
    log.info("fromAddressString: " + fromAddressString.trim());

    // Find Member user callerId
    String queryMembers =  " select from " + Member.class.getName() + 
    " where username == '" + callerId.trim() + "'";
    List<Member> members = (List<Member>) pm.newQuery(queryMembers).execute();
    Member m = members.get(0);
 
    // Find most recent alert
    String queryAlerts = " select from " + Alert.class.getName() + 
    " where alertId == " + alertId + " order by timeStamp desc ";
    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlerts).execute();
    
    try {
      
      if (alertText.toString().contains("resendAlertText")) {
        String msgBody = "Alert Msg: " + alerts.get(0).getalertMsgString();
        
        try {
          
          msg.setFrom(new InternetAddress("jreilly@gmail.com", "responderIQ Admin"));
          msg.addRecipient(Message.RecipientType.TO,  
                  new InternetAddress(fromAddressString, "Responder"));
          msg.setSubject("riqAlertInit:");
          msg.setText(msgBody);
          Transport.send(msg);
          
        } catch (MessagingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (UnsupportedEncodingException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    } catch (MessagingException e) {
          // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
    
  }
    
    
  
    
  private String getText(Part p) throws MessagingException, IOException {
    log.info("Message S Zero");
    
    log.info("Inside MailServlet getText");

    if (p.isMimeType("text/*")) {
      String s = (String)p.getContent();
      log.info("Message S1: " + s);
      log.info("Message S1: " + s);
      boolean textIsHtml = p.isMimeType("text/html");
      return s;
    }

    if (p.isMimeType("multipart/alternative")) {
      Multipart mp = (Multipart)p.getContent();
      String text = null;
      for (int i = 0; i < mp.getCount(); i++) {
        Part bp = mp.getBodyPart(i);
        if (bp.isMimeType("text/plain")) {
          if (text == null)
            text = getText(bp);
          log.info("Message S2: " + text);
          continue;
        } else if (bp.isMimeType("text/html")) {
          String s = getText(bp);
          if (s != null)
            log.info("Message S3: " + s);
          return s;
        } else if (bp.isMimeType("message/rfc822")) {
          Object nestedObject = "";   
          nestedObject = bp.getContent();
          Multipart nestedPart = (Multipart)nestedObject;
          BodyPart nestedBodyPart = nestedPart.getBodyPart(0);
          String s = getText(nestedBodyPart); 
          if (s != null)
            log.info("Message Nested: " + s);
          return s;
        } else {
          log.info("Message nada");
          return getText(bp);
        }
      }
      return text;

    } else if (p.isMimeType("multipart/*")) {
      Multipart mp = (Multipart)p.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        String s = getText(mp.getBodyPart(i));
        if (s != null) {
          log.info("Message S4: " + s);
          return s;
        }
      }
    }
    return null;
  }


  
    
    
}